//
//  MKUserAccount.m
//  Weibo_OC
//
//  Created by mac on 16/1/13.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MKUserAccount.h"

@implementation MKUserAccount


+ (instancetype)userAccountWithDict:(NSDictionary *)dict {
    
    MKUserAccount *model = [[MKUserAccount alloc] init];
    
    [model setValuesForKeysWithDictionary:dict];
    
    return model;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super init]) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.uid = [aDecoder decodeObjectForKey:@"uid"];
        self.access_token = [aDecoder decodeObjectForKey:@"access_token"];
        self.avatar_large = [aDecoder decodeObjectForKey:@"avatar_large"];
        self.expires_in = [aDecoder decodeDoubleForKey:@"expires_in"];
        _expires_date = [aDecoder decodeObjectForKey:@"expires_date"];
    }
    
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeObject:self.uid forKey:@"uid"];
    [aCoder encodeObject:self.access_token forKey:@"access_token"];
    [aCoder encodeObject:self.avatar_large forKey:@"avatar_large"];
    [aCoder encodeDouble:self.expires_in forKey:@"expires_in"];
    [aCoder encodeObject:self.expires_date forKey:@"expires_date"];
}

- (void)saveUserInfo {
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *filePath = [docPath stringByAppendingPathComponent:@"userInfo.plist"];
    
    [NSKeyedArchiver archiveRootObject:self toFile:filePath];
    
    NSLog(@"%@",filePath);
}

+ (MKUserAccount *)loadUserInfo {
    
    MKUserAccount *model;
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *filePath = [docPath stringByAppendingPathComponent:@"userInfo.plist"];
    
    model = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    if ([model.expires_date compare:[[NSDate alloc] init]] == NSOrderedDescending) {
        return  model;
    }
    
    return nil;
}


- (void)setExpires_in:(NSTimeInterval)expires_in {
    _expires_in = expires_in;
    
    _expires_date = [NSDate dateWithTimeIntervalSinceNow:_expires_in];
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key{}
@end
